const express = require('express');
const http = require('http');
const path = require('path');
const cors = require('cors');
const { Server } = require('socket.io');

// 创建Express应用
const app = express();
const server = http.createServer(app);

// 启用CORS
app.use(cors());
//
// 设置Socket.IO，允许跨域请求
const io = new Server(server, {
  cors: {
    origin: "*",
    methods: ["GET", "POST"]
  },
  // 添加pingTimeout设置，防止连接意外断开
  pingTimeout: 20000
});

// 添加服务器状态路由，用于测试服务器是否在线
app.get('/status', (req, res) => {
  res.json({
    status: 'online',
    uptime: process.uptime(),
    rooms: Object.keys(rooms).length,
    connections: io.engine.clientsCount
  });
});

// 存储房间信息
const rooms = {};

// 为房间创建默认房间，方便测试
function createDefaultRooms() {
  // 创建几个默认房间
  const defaultRooms = [
    {id: 'room1', name: '会议室 1'},
  ]

  defaultRooms.forEach(room => {
    rooms[room.id] = {
      roomId: room.id,
      roomName: room.name,
      users: [],
      hasSharing: false,
      sharingUserId: null
    };
  });

  console.log('已创建默认房间列表:', defaultRooms);
}

// 启动时创建默认房间
createDefaultRooms();

io.on('connection', (socket) => {
  console.log('用户已连接! Socket ID:', socket.id, 'IP地址:', socket.handshake.address);

  // 获取房间列表
  socket.on('get-room-list', () => {
    console.log('用户请求房间列表, Socket ID:', socket.id);

    // 构建包含房间信息的数组
    const roomList = Object.values(rooms).map(room => ({
      roomId: room.roomId,
      roomName: room.roomName,
      userCount: room.users.length,
      hasSharing: room.hasSharing
    }));

    console.log('发送房间列表:', roomList);
    // 发送房间列表给请求的客户端
    socket.emit('room-list', roomList);
  });

  // 创建或加入房间
  socket.on('join-room', (roomId, userId) => {
    console.log(`用户 ${userId} (Socket: ${socket.id}) 加入房间 ${roomId}`);

    // 存储用户的当前房间ID，方便后续处理
    socket.roomId = roomId;
    socket.userId = userId;

    // 如果房间不存在，创建它
    if (!rooms[roomId]) {
      console.log(`创建新房间: ${roomId}`);
      rooms[roomId] = {
        roomId: roomId,
        roomName: `房间 ${roomId}`,
        users: [],
        hasSharing: false,
        sharingUserId: null
      };
    }

    // 将用户添加到房间
    rooms[roomId].users.push(userId);
    socket.join(roomId);
    console.log(`房间 ${roomId} 当前用户: ${rooms[roomId].users.join(', ')}`);

    // 通知房间内的其他用户有新用户加入
    socket.to(roomId).emit('user-connected', userId);
    console.log(`通知房间 ${roomId} 中的其他用户: 新用户 ${userId} 已连接`);

    // 如果房间有人在共享，通知新加入的用户
    if (rooms[roomId].hasSharing) {
      console.log(`通知新用户 ${userId}: 用户 ${rooms[roomId].sharingUserId} 正在共享屏幕`);
      socket.emit('user-started-sharing', rooms[roomId].sharingUserId);
    }
  });

  // 离开房间
  socket.on('leave-room', (roomId, userId) => {
    console.log(`用户 ${userId} (Socket: ${socket.id}) 离开房间 ${roomId}`);

    if (rooms[roomId]) {
      // 从房间中移除用户
      rooms[roomId].users = rooms[roomId].users.filter(id => id !== userId);
      console.log(`房间 ${roomId} 更新后的用户列表: ${rooms[roomId].users.join(', ')}`);

      // 如果离开的是正在共享的用户，更新共享状态
      if (rooms[roomId].sharingUserId === userId) {
        rooms[roomId].hasSharing = false;
        rooms[roomId].sharingUserId = null;
        console.log(`共享用户 ${userId} 离开，停止房间 ${roomId} 的共享`);
        // 通知房间中的其他用户共享已停止
        socket.to(roomId).emit('user-stopped-sharing', userId);
      }

      // 通知房间中的其他用户
      socket.to(roomId).emit('user-disconnected', userId);
      console.log(`通知房间 ${roomId} 的其他用户: 用户 ${userId} 已断开连接`);

      // 从房间中移除
      socket.leave(roomId);

      // 如果房间为空且不是默认房间，删除它
      if (rooms[roomId].users.length === 0 && !isDefaultRoom(roomId)) {
        console.log(`房间 ${roomId} 为空，删除该房间`);
        delete rooms[roomId];
      }
    }
  });

  // 处理信令消息
  socket.on('offer', (roomId, userId, offer) => {
    console.log(`用户 ${userId} 在房间 ${roomId} 发送提议给用户 ${offer.targetUserId}`);
    socket.to(roomId).emit('offer', userId, offer);
  });

  socket.on('answer', (roomId, userId, answer) => {
    console.log(`用户 ${userId} 在房间 ${roomId} 发送应答给用户 ${answer.targetUserId}`);
    socket.to(roomId).emit('answer', userId, answer);
  });

  socket.on('ice-candidate', (roomId, userId, candidate) => {
    console.log(`用户 ${userId} 在房间 ${roomId} 发送ICE候选给用户 ${candidate.targetUserId}`);
    socket.to(roomId).emit('ice-candidate', userId, candidate);
  });

  // 开始/停止屏幕共享
  socket.on('start-sharing', (roomId, userId) => {
    console.log(`用户 ${userId} (Socket: ${socket.id}) 开始在房间 ${roomId} 共享屏幕`);

    if (rooms[roomId]) {
      rooms[roomId].hasSharing = true;
      rooms[roomId].sharingUserId = userId;
      console.log(`房间 ${roomId} 更新共享状态: hasSharing=true, sharingUserId=${userId}`);
    }

    socket.to(roomId).emit('user-started-sharing', userId);
    console.log(`通知房间 ${roomId} 的其他用户: 用户 ${userId} 开始共享屏幕`);

    // 通知所有客户端更新房间列表
    updateRoomListForAllClients();
  });

  socket.on('stop-sharing', (roomId, userId) => {
    console.log(`用户 ${userId} (Socket: ${socket.id}) 停止在房间 ${roomId} 共享屏幕`);

    if (rooms[roomId]) {
      rooms[roomId].hasSharing = false;
      rooms[roomId].sharingUserId = null;
      console.log(`房间 ${roomId} 更新共享状态: hasSharing=false, sharingUserId=null`);
    }

    socket.to(roomId).emit('user-stopped-sharing', userId);
    console.log(`通知房间 ${roomId} 的其他用户: 用户 ${userId} 停止共享屏幕`);

    // 通知所有客户端更新房间列表
    updateRoomListForAllClients();
  });

  // 用户断开连接
  socket.on('disconnect', () => {
    const roomId = socket.roomId;
    const userId = socket.userId;

    if (roomId && userId) {
      console.log(`用户 ${userId} (Socket: ${socket.id}) 断开连接，从房间 ${roomId} 移除`);

      if (rooms[roomId]) {
        // 从房间中移除用户
        rooms[roomId].users = rooms[roomId].users.filter(id => id !== userId);
        console.log(`房间 ${roomId} 更新后的用户列表: ${rooms[roomId].users.join(', ')}`);

        // 如果断开的是正在共享的用户，更新共享状态
        if (rooms[roomId].sharingUserId === userId) {
          rooms[roomId].hasSharing = false;
          rooms[roomId].sharingUserId = null;
          console.log(`共享用户 ${userId} 断开连接，停止房间 ${roomId} 的共享`);
          // 通知房间中的其他用户共享已停止
          socket.to(roomId).emit('user-stopped-sharing', userId);
        }

        // 通知房间中的其他用户
        socket.to(roomId).emit('user-disconnected', userId);
        console.log(`通知房间 ${roomId} 的其他用户: 用户 ${userId} 已断开连接`);

        // 如果房间为空且不是默认房间，删除它
        if (rooms[roomId].users.length === 0 && !isDefaultRoom(roomId)) {
          console.log(`房间 ${roomId} 为空，删除该房间`);
          delete rooms[roomId];
        }

        // 通知所有客户端更新房间列表
        updateRoomListForAllClients();
      }
    } else {
      console.log(`未知用户断开连接, Socket ID: ${socket.id}`);
    }
  });

  // 新增：获取房间内的用户列表
  socket.on('get-room-users', (roomId) => {
    console.log(`用户 ${socket.userId} 请求房间 ${roomId} 的用户列表`);

    if (rooms[roomId]) {
      // 过滤掉当前用户
      const otherUsers = rooms[roomId].users.filter(userId => userId !== socket.userId);
      console.log(`向用户 ${socket.userId} 发送房间 ${roomId} 的用户列表:`, otherUsers);

      // 发送给请求的客户端
      socket.emit('room-users', roomId, otherUsers);
    } else {
      console.log(`用户 ${socket.userId} 请求的房间 ${roomId} 不存在`);
    }
  });
});

// 定期向所有连接的客户端发送更新的房间列表
function updateRoomListForAllClients() {
  // 构建房间列表
  const roomList = Object.values(rooms).map(room => ({
    roomId: room.roomId,
    roomName: room.roomName,
    userCount: room.users.length,
    hasSharing: room.hasSharing
  }));

  // 向所有客户端广播房间列表
  io.emit('room-list', roomList);
  console.log('广播更新的房间列表给所有客户端:', roomList);
}

// 检查是否为默认房间
function isDefaultRoom(roomId) {
  return ['room1', 'room2', 'room3', 'room4', 'room5'].includes(roomId);
}

// 每30秒向所有客户端发送一次房间列表更新
setInterval(updateRoomListForAllClients, 30000);

// 启动服务器
const PORT = process.env.PORT || 5000; // 改为5000端口，避免与React前端的3000端口冲突
server.listen(PORT, () => {
  console.log(`信令服务器运行在 http://localhost:${PORT}`);
  console.log(`局域网访问: http://${getLocalIpAddress()}:${PORT}`);
  console.log('等待客户端连接...');
});

// 获取本地IP地址
function getLocalIpAddress() {
  const { networkInterfaces } = require('os');
  const nets = networkInterfaces();

  for (const name of Object.keys(nets)) {
    for (const net of nets[name]) {
      // 跳过内部IP和非IPv4地址
      if (net.family === 'IPv4' && !net.internal) {
        return net.address;
      }
    }
  }
  return '0.0.0.0'; // 默认回退
}
